from datetime import datetime
from typing import Any, List, Optional
import pydantic
from sqlalchemy import Column, Integer, String, DateTime, Float, Boolean, JSON, func

from hetong.db.base import Base
from api_server.auth_util import settings
from api_server.utils import BaseResponse

from datetime import datetime
class KnowledgeFileModel(Base):
    """
    知识文件模型
    """
    __tablename__ = 'knowledge_file'
    id = Column(Integer, primary_key=True, autoincrement=True, comment='知识文件ID')
    file_name = Column(String(255), comment='文件名')
    file_ext = Column(String(10), comment='文件扩展名')
    kb_name = Column(String(50), comment='所属知识库名称')
    document_loader_name = Column(String(50), comment='文档加载器名称')
    text_splitter_name = Column(String(50), comment='文本分割器名称')
    file_version = Column(Integer, default=1, comment='文件版本')
    file_mtime = Column(Float, default=0.0, comment="文件修改时间")
    file_size = Column(Integer, default=0, comment="文件大小")
    file_status = Column(Integer, default=0, comment="文件状态0-未开始，1-识别中，2-识别完成,-1解析失败")
    custom_docs = Column(Boolean, default=False, comment="是否自定义docs")
    docs_count = Column(Integer, default=0, comment="切分文档数量")
    create_time = Column(DateTime, default=datetime.now(), comment='创建时间')
    end_time = Column(DateTime, default=datetime.now(), comment='完成时间')
    create_user_id = Column(Integer, default=0, comment='创建者id')
    create_user_name = Column(String(50), default='', comment='创建者名称(冗余)')

    def __repr__(self):
        return f"<KnowledgeFile(id='{self.id}', file_name='{self.file_name}', file_ext='{self.file_ext}', kb_name='{self.kb_name}', document_loader_name='{self.document_loader_name}', text_splitter_name='{self.text_splitter_name}', file_version='{self.file_version}', create_time='{self.create_time}')>"


class KnowledgeFileBean(pydantic.BaseModel):
    id: int = pydantic.Field(1, description='知识文件ID')
    file_name: Any = pydantic.Field('', description='文件名')
    file_ext: Any = pydantic.Field('', description='文件扩展名')
    kb_name: Any = pydantic.Field('', description='所属知识库名称')
    document_loader_name: Any = pydantic.Field('', description='文档加载器名称')
    text_splitter_name: Any = pydantic.Field('', description='文本分割器名称')
    file_version: Any = pydantic.Field(1, description='文件版本')
    file_mtime: Any = pydantic.Field(0.0, description="文件修改时间")
    file_size: Any = pydantic.Field(0, description="文件大小")
    file_status: Optional[int] = pydantic.Field(0, description="文件状态0-未开始，1-识别中，2-识别完成")
    custom_docs: Any = pydantic.Field(False, description="是否自定义docs")
    docs_count: Any = pydantic.Field(0, description="切分文档数量")
    create_time: Any = pydantic.Field(None, description='创建时间')
    create_user_id: Any = pydantic.Field(0, description='创建者id')
    create_user_name: Any = pydantic.Field('', description='创建者名称(冗余)')

    class Config:
        orm_mode = True
        json_encoders = {
            datetime: lambda v: v.strftime(settings.datetime_format)
        }


class ListKbFileResponse(BaseResponse):
    data: List[KnowledgeFileBean] = pydantic.Field(..., description="知识库文档对象")
    page: int = pydantic.Field(1, description="分页页码")
    pageSize: int = pydantic.Field(10, description="分页条数")
    total: int = pydantic.Field(0, description="总条数")

    class Config:
        schema_extra = {
            "example": {
                "code": 200,
                "msg": "success",
                "data": [
                    {
                        "id": 36,
                        "file_name": "附件十：《项目团队服务成员登记表》.xls",
                        "file_ext": ".xls",
                        "kb_name": "hetong",
                        "document_loader_name": "UnstructuredExcelLoader",
                        "text_splitter_name": "ChineseRecursiveTextSplitter",
                        "file_version": 1,
                        "file_mtime": 1716433690.3004205,
                        "file_size": 34816,
                        "file_status": 0,
                        "custom_docs": False,
                        "docs_count": 14,
                        "create_time": "2024-05-29T03:59:19.243032",
                        "create_user_id": 0,
                        "create_user_name": 'admin'
                    },
                    {
                        "id": 33,
                        "file_name": "附件九：《中国移动通用网络与信息安全责任条款》.docx",
                        "file_ext": ".docx",
                        "kb_name": "hetong",
                        "document_loader_name": "RapidOCRDocLoader",
                        "text_splitter_name": "ChineseRecursiveTextSplitter",
                        "file_version": 1,
                        "file_mtime": 1716433690.2844205,
                        "file_size": 105731,
                        "file_status": 0,
                        "custom_docs": False,
                        "docs_count": 7,
                        "create_time": "2024-05-29T03:59:14.766309",
                        "create_user_id": 1,
                        "create_user_name": "admin"
                    }],
            }
        }


class FileDocModel(Base):
    """
    文件-向量库文档模型
    """
    __tablename__ = 'file_doc'
    id = Column(Integer, primary_key=True, autoincrement=True, comment='ID')
    kb_name = Column(String(50), comment='知识库名称')
    file_name = Column(String(255), comment='文件名称')
    doc_id = Column(String(50), comment="向量库文档ID")
    meta_data = Column(JSON, default={})

    def __repr__(self):
        return f"<FileDoc(id='{self.id}', kb_name='{self.kb_name}', file_name='{self.file_name}', doc_id='{self.doc_id}', metadata='{self.meta_data}')>"
